<template>
  <div>
    <h2 class="mb-4">短信配置</h2>
    <a-form :model="form" layout="vertical">
      <a-form-item label="短信服务商" name="provider">
        <a-select v-model:value="form.provider" placeholder="请选择短信服务商">
          <a-select-option value="aliyun">阿里云短信</a-select-option>
          <a-select-option value=mock>模拟短信</a-select-option>
        </a-select>
      </a-form-item>

      <template v-if="form.provider === 'aliyun'">
        <a-form-item label="AccessKey ID" name="accessKeyId">
          <a-input v-model:value="form.accessKeyId" placeholder="请输入AccessKey ID" />
        </a-form-item>
        <a-form-item label="AccessKey Secret" name="accessKeySecret">
          <a-input-password v-model:value="form.accessKeySecret" placeholder="请输入AccessKey Secret" />
        </a-form-item>
        <a-form-item label="短信签名" name="signName">
          <a-input v-model:value="form.signName" placeholder="请输入短信签名" />
        </a-form-item>
        <a-form-item label="模板ID" name="templateCode">
          <a-input v-model:value="form.templateCode" placeholder="请输入模板ID" />
        </a-form-item>
      </template>

      <template v-if="form.provider === 'mock'">
        <a-form-item label="SecretId" name="secretId">
          <a-input v-model:value="form.secretId" placeholder="请输入SecretId" />
        </a-form-item>
        <a-form-item label="SecretKey" name="secretKey">
          <a-input-password v-model:value="form.secretKey" placeholder="请输入SecretKey" />
        </a-form-item>
        <a-form-item label="短信签名" name="signName">
          <a-input v-model:value="form.signName" placeholder="请输入短信签名" />
        </a-form-item>
        <a-form-item label="模板ID" name="templateId">
          <a-input v-model:value="form.templateId" placeholder="请输入模板ID" />
        </a-form-item>
      </template>


      <a-form-item>
        <a-space>
          <a-button type="primary" @click="handleSave">保存配置</a-button>
          <a-button @click="handleTest">测试连接</a-button>
        </a-space>
      </a-form-item>
    </a-form>

    <!-- 测试区域 -->
    <div class="test-area">
      <a-collapse v-model:activeKey="activeKey" :bordered="false">
        <a-collapse-panel key="1" :show-arrow="false">
          <template #header>
            <div class="collapse-header">
              <h2 class="mb-0">短信测试</h2>
              <a-button type="link" @click.stop="toggleTest">
                {{ isExpanded ? '收起' : '展开' }}
                <down-outlined :class="{ 'rotate-icon': isExpanded }" />
              </a-button>
            </div>
          </template>

          <a-form :model="testForm" layout="vertical">
            <a-form-item label="手机号码" name="phone">
              <a-input v-model:value="testForm.phone" placeholder="请输入接收测试短信的手机号码" />
            </a-form-item>
            <a-form-item label="模板参数" name="templateParams">
              <a-textarea v-model:value="testForm.templateParams" placeholder='请输入模板参数，JSON格式，例如：{"code":"123456"}' />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="handleSendTest" :loading="sending">
                发送测试短信
              </a-button>
            </a-form-item>
          </a-form>

          <!-- 发送记录 -->
          <div class="send-history mt-4">
            <h3 class="mb-4">发送记录</h3>
            <a-table
              :columns="columns"
              :data-source="sendHistory"
              :pagination="{ pageSize: 5 }"
              size="small"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'status'">
                  <a-tag :color="record.status === 'success' ? 'success' : 'error'">
                    {{ record.status === 'success' ? '发送成功' : '发送失败' }}
                  </a-tag>
                </template>
              </template>
            </a-table>
          </div>
        </a-collapse-panel>
      </a-collapse>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { DownOutlined } from '@ant-design/icons-vue'
import axios from 'axios'
import type { AxiosError } from 'axios'

const form = reactive({
  provider: '',
  // 阿里云配置
  accessKeyId: '',
  accessKeySecret: '',
  signName: '',
  templateCode: '',
  // 模拟配置
  secretId: '',
  secretKey: '',
  sdkAppId: '',
  templateId: '',
})

// 测试表单
const testForm = reactive({
  phone: '',
  templateParams: '',
})

// 发送状态
const sending = ref(false)

// 发送历史
interface SendRecord {
  id: number
  phone: string
  template: string
  params: string
  status: 'success' | 'error'
  time: string
  message?: string
}

const sendHistory = ref<SendRecord[]>([])

// 表格列定义
const columns = [
  {
    title: '手机号码',
    dataIndex: 'phone',
    key: 'phone',
  },
  {
    title: '模板',
    dataIndex: 'template',
    key: 'template',
  },
  {
    title: '参数',
    dataIndex: 'params',
    key: 'params',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '时间',
    dataIndex: 'time',
    key: 'time',
  },
  {
    title: '备注',
    dataIndex: 'message',
    key: 'message',
  },
]

// 获取配置
const fetchConfig = async () => {
  if (!form.provider) {
    // 未选择服务商时不请求
    return
  }
  try {
    const response = await axios.get('/api/sms/config')
    const config = response.data
    form.provider = config.type || ''
    if (config.type === 'aliyun') {
      form.accessKeyId = config.accessKeyId || ''
      form.accessKeySecret = config.accessKeySecret || ''
      form.signName = config.signName || ''
      form.templateCode = config.templateId || ''
    } else if (config.type === 'mock') {
      form.secretId = config.accessKeyId || ''
      form.secretKey = config.accessKeySecret || ''
      form.signName = config.signName || ''
      form.templateId = config.templateId || ''
    }
  } catch (error) {
    message.error('获取配置失败')
  }
}

// 在组件挂载时获取配置
onMounted(() => {
  fetchConfig()
})

const handleSave = async () => {
  try {
    if (!form.provider) {
      message.error('请选择短信服务商')
      return
    }

    if (!form.signName) {
      message.error('请填写短信签名')
      return
    }

    if (form.provider === 'aliyun' && !form.templateCode) {
      message.error('请填写阿里云短信模板代码')
      return
    }

    if (form.provider === 'mock' && !form.templateId) {
      message.error('请填写模拟短信模板代码')
      return
    }

    const config = {
      type: form.provider,
      accessKeyId: form.provider === 'aliyun' ? form.accessKeyId : form.secretId,
      accessKeySecret: form.provider === 'aliyun' ? form.accessKeySecret : form.secretKey,
      signName: form.signName,
      templateId: form.provider === 'aliyun' ? form.templateCode : form.templateId,
      defaultTemplateId: form.provider === 'aliyun' ? form.templateCode : form.templateId,
      templateParams: form.templateParams
    }
    
    await axios.post('/api/sms/switch', config)
    
    // 保存成功后，将配置数据保存到本地存储
    localStorage.setItem('smsConfig', JSON.stringify({
      provider: form.provider,
      accessKeyId: form.provider === 'aliyun' ? form.accessKeyId : form.secretId,
      accessKeySecret: form.provider === 'aliyun' ? form.accessKeySecret : form.secretKey,
      signName: form.signName,
      templateCode: form.provider === 'aliyun' ? form.templateCode : '',
      templateId: form.provider === 'mock' ? form.templateId : '',
      secretId: form.provider === 'mock' ? form.secretId : '',
      secretKey: form.provider === 'mock' ? form.secretKey : '',
      templateParams: form.templateParams
    }))
    
    message.success('短信配置保存成功')
  } catch (error: unknown) {
    const axiosError = error as AxiosError<{ message: string }>
    message.error('保存配置失败：' + (axiosError.response?.data?.message || axiosError.message))
  }
}

// 在组件挂载时，从本地存储加载配置
onMounted(() => {
  const savedConfig = localStorage.getItem('smsConfig')
  if (savedConfig) {
    try {
      const config = JSON.parse(savedConfig)
      form.provider = config.provider
      if (config.provider === 'aliyun') {
        form.accessKeyId = config.accessKeyId
        form.accessKeySecret = config.accessKeySecret
        form.templateCode = config.templateCode
      } else if (config.provider === 'mock') {
        form.secretId = config.secretId
        form.secretKey = config.secretKey
        form.templateId = config.templateId
      }
      form.signName = config.signName
    } catch (e) {
      console.error('加载保存的配置失败:', e)
    }
  }
})

const handleTest = () => {
  // TODO: 实现发送测试短信功能
  message.success('测试短信发送成功')
}

// 折叠面板状态
const activeKey = ref<string[]>([])
const isExpanded = ref(false)

// 切换折叠状态
const toggleTest = () => {
  isExpanded.value = !isExpanded.value
  activeKey.value = isExpanded.value ? ['1'] : []
}

// 发送测试短信
const handleSendTest = async () => {
  if (!testForm.phone) {
    message.error('请输入手机号码')
    return
  }

  if (!form.templateCode && form.provider === 'aliyun') {
    message.error('请先配置短信模板代码')
    return
  }

  if (!form.templateId && form.provider === 'mock') {
    message.error('请先配置短信模板代码')
    return
  }

  if (!testForm.templateParams) {
    message.error('请填写模板参数')
    return
  }

  try {
    // 验证JSON格式
    JSON.parse(testForm.templateParams)
  } catch (e) {
    message.error('模板参数格式不正确，请使用正确的JSON格式')
    return
  }

  try {
    sending.value = true
    const response = await axios.post('/api/sms/send', {
      phone: testForm.phone,
      templateParams: testForm.templateParams
    })
    
    const record: SendRecord = {
      id: Date.now(),
      phone: testForm.phone,
      template: response.data.templateId || '默认模板',
      params: testForm.templateParams || '',
      status: response.data.success ? 'success' : 'error',
      time: response.data.sendTime || new Date().toLocaleString(),
      message: response.data.success ? '发送成功' : response.data.message
    }
    sendHistory.value.unshift(record)
    message.success('测试短信发送成功')
  } catch (error: unknown) {
    const axiosError = error as AxiosError<{ message: string }>
    message.error('测试短信发送失败：' + (axiosError.response?.data?.message || axiosError.message))
  } finally {
    sending.value = false
  }
}
</script>

<style scoped>
.mb-4 {
  margin-bottom: 16px;
}
.mt-4 {
  margin-top: 16px;
}
.test-area {
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}
.send-history {
  margin-top: 24px;
}
.collapse-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}
.collapse-header h2 {
  margin: 0;
}
.rotate-icon {
  transform: rotate(180deg);
  transition: transform 0.3s;
}
:deep(.ant-collapse-header) {
  padding: 0 !important;
}
:deep(.ant-collapse-content) {
  border-top: none !important;
}
:deep(.ant-collapse-item) {
  border: none !important;
}
</style>

